package com.wang.scacodetest.controller.iphone;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wang.scacodetest.bean.Ajax;
import com.wang.scacodetest.domain.UserToken;
import com.wang.scacodetest.service.UserTokenService;
import com.wang.scacodetest.websocker.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.Date;

@RestController
@RequestMapping("iphone/scacode")
public class IphoneScacodeController {
    @Autowired
    private UserTokenService userTokenService;
    @Autowired
    private WebSocketServer webSocketServer;

    @PostMapping("bindUserIdAndToken")
    public Ajax bindUserIdAndToken(String userId,String token){
        if(StrUtil.isEmpty(token)){
            return Ajax.success("不好意思，token值必需传到");
        }
        UserToken userToken=userTokenService.getOne(
                new LambdaQueryWrapper<UserToken>()
                .eq(UserToken::getUuid,token)
        );

        //扫码的限制时间只有3分钟
        LocalDateTime tokenDateTime=userToken.getCreateTime().plusMinutes(3);
        LocalDateTime now=LocalDateTime.now();
        if(now.isAfter(tokenDateTime)){
            Ajax ajax=new Ajax(500,"码过期了，请重新扫下，谢谢！");
            String json=  JSONObject.toJSONString(ajax);
            webSocketServer.sendMessageBySid(token,json);
            return Ajax.success("扫码失败了");
        }else {
            userToken.setLoginTime(LocalDateTime.now());
            userTokenService.updateById(userToken);
            Ajax ajax=new Ajax(200,"成功了！",userId);
            String json=JSONObject.toJSONString(ajax);
            webSocketServer.sendMessageBySid(token,json);
            return Ajax.success("扫码成功了！");
        }
    }
}
